#include "additem.h"
#include "ui_additem.h"

AddItem::AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddItem)
{
    ui->setupUi(this);

    table=TD_CHANGELOG;
    updateEntry();
}

AddItem::~AddItem()
{
    delete ui;
}

void AddItem::updateEntry()
{
    if(!entries.isEmpty())
        entries.clear();

    entries=sp_getCategory("entry",table);
    if(!entries.isEmpty())
    {
        ui->entries->addItems(entries);
    }
    ui->entries->addItem(MANUAL_INPUT);
    ui->entries->setCurrentIndex(-1);
}

void AddItem::on_entries_currentTextChanged(const QString &text)
{
    if(text == MANUAL_INPUT)
    {
        ui->entry->clear();
        ui->entry->setEnabled(true);
    }
    else {
        ui->entry->setText(text);
        ui->entry->setEnabled(false);
    }
}

void AddItem::prepare(const QString &entry)
{
    if(entries.contains(entry))
        ui->entries->setCurrentText(entry);

    QSqlQuery query;
    query.exec(QString("select version from %1 where entry='%2' ORDER BY version DESC")
               .arg(table)
               .arg(entry));
    if(query.next())
    {
        double version=query.value(0).toDouble();
        if(version > 1000)
            ui->version->setValue(version + 0.1);
    }
}

bool AddItem::addItem(const QString &entry, double version, const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (entry,date_,version,detail) values (?,?,?,?)")
                  .arg(table));
    query.addBindValue(entry);
    query.addBindValue(Today);
    query.addBindValue(version);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddItem::on_btn_submit_clicked()
{
    QString entry=ui->entry->text().trimmed();
    double version=ui->version->value();
    QString detail=ui->detail->toPlainText();

    if(entry.isEmpty() || version < 1000 || detail.isEmpty())
        return;

    if(addItem(entry,version,detail))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT;
}
